import 'dart:typed_data';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import 'dart:async';

import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';

class Player extends StatefulWidget {
  final src;
  final text;
  final color;
  final autoplay;
  Player({this.src,this.text,this.color,this.autoplay});
  @override
  AudioPlayerState createState() =>  AudioPlayerState();
}

class AudioPlayerState extends State<Player>{
  RxBool playing = false.obs;
  String lastSrc = '';
  var color;
  late AudioPlayer audioPlayer;
  late StreamSubscription _audioPlayerStateSubscription;
  late StreamSubscription _audioPlayerStateSubscriptionEnd;
  @override
  void initState() {
    super.initState();
    initAudio();
  }

  @override
  void dispose(){
    stop();
    super.dispose();
  }

  @override
  didUpdateWidget(oldWidget){
    if(lastSrc != widget.src && widget.autoplay){
      initAudio();
    }
  }

  Future play(url) async {
    try{
      String ans = url.replaceAll('http', 'https');
      ans = ans.replaceAll('httpss', 'https');
      // print(ans);
      final dio = Dio();
      final response = await dio.get(ans, options: Options(responseType: ResponseType.bytes));
      final Uint8List audioData = response.data;
      final tempDir = await getTemporaryDirectory();
      final file = await File('${tempDir.path}/audio.mp3').writeAsBytes(audioData);
      // print(file.path);
      await audioPlayer.play(UrlSource(file.path));
      // await audioPlayer.play(UrlSource(ans));
      // int result = await audioPlayer.play(ans);
      // if (result == 1) {
      //   // success
      //   print(url);
      //   print('play success');
      // } else {
      //   print('play failed');
      // }
      if(mounted){
        lastSrc = ans;
        playing.value = true;
      }
    }catch(e){
      // print(e);
      stop();
    }
  }

  Future stop() async {
    try{
      await audioPlayer.stop();
      // int result = await audioPlayer.stop();
      // if (result == 1) {
      //   // success
      //   print('pause success');
      // } else {
      //   print('pause failed');
      // }
      if(mounted){
        playing.value = false;
      }
    }catch(e){
      if(mounted){
        playing.value = false;
      }
    }
  }

  void audioController(url){
    if(playing.value){
      stop();
    }else{
      play(url);
    }
  }

  void initAudio(){
    // print("initAudio");
    audioPlayer = AudioPlayer();
  }

  @override
  Widget build(BuildContext context) {
    return  GestureDetector(
      child:  Container(
        // width: double.infinity,
        // color: Colors.black12,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            // Expanded(child: Icon(
            //   playing ? Icons.pause_circle_outline : Icons.play_circle_outline,
            //   color: widget.color,
            //   size: 12.0,
            // ),),
            Obx(()=>Icon(
              playing.value ? Icons.pause_circle_outline : Icons.play_circle_outline,
              color: widget.color,
              size: 18.0,
            )),
            Container(
              constraints: BoxConstraints(maxWidth: (MediaQuery.of(context).size.width -120) * 0.4),
              child: Text.rich(
                  TextSpan(
                      children:[
                        TextSpan(text: ' /'+widget.text+'/',style: TextStyle(color: widget.color,fontSize: 16)),
                      ]
                  )
              ),
            )

            // Expanded(child: Text.rich(
            //     TextSpan(
            //         children:[
            //           TextSpan(text: ' /'+widget.text+'/',style: TextStyle(color: widget.color,fontSize: 16)),
            //         ]
            //     )
            // ),),
            // Text(' /'+widget.text+'/',style:  TextStyle(fontSize: 12.0,color: widget.color),),
          ],
        ),
      ),
      onTap: (){
        audioPlayer =  AudioPlayer();
        _audioPlayerStateSubscription = audioPlayer.onPlayerStateChanged.listen((s){
          // print("PlayerState------------->$s");
          if(s == PlayerState.completed){
            stop();
          }
        }, onError: (msg){
          // print("onError------------->$msg");
          stop();
        });
        _audioPlayerStateSubscriptionEnd = audioPlayer.onPlayerComplete.listen((_){
          stop();
        }, onError: (msg){
          // print("onError------------->$msg");
          stop();
        });
        if(widget.src.isNotEmpty){
          audioController(widget.src);
        }
      },
    );
  }
}